package com.material.common.exception;

import com.material.common.entity.ResultResponse;
import com.material.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GloablExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GloablExceptionHandler.class);

    /**
     * 业务异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public ResultResponse handleBizException(ServiceException e)
    {
        log.error(e.getMessage(), e);
        String msg = e.getMessage();
        if (StringUtils.isBlank(msg))
        {
            msg = "服务器出错";
        }
        return new ResultResponse(500, msg);
    }

    /**
     * 登录超时
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(LoginExpiredException.class)
    public ResultResponse handleBizException(LoginExpiredException e)
    {
        log.error(e.getMessage(), e);
        String msg = e.getMessage();
        if (StringUtils.isBlank(msg))
        {
            msg = "服务器出错";
        }
        return new ResultResponse(501, msg);
    }

    /**
     * 请求方式不支持
     */
    @ResponseBody
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public ResultResponse handleException(HttpRequestMethodNotSupportedException e)
    {
        log.error(e.getMessage(), e);
        return ResultResponse.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResultResponse notFount(RuntimeException e)
    {
        log.error("运行时异常:", e);
        String msg = "系统繁忙，请稍后重试";
        return ResultResponse.error("运行时异常:" + msg);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultResponse handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        String msg = e.getMessage();
        if (StringUtils.isBlank(msg))
        {
            msg = "服务器出错";
        }
        return new ResultResponse(500, msg);
    }
}
